package com.clp.protocol.iec104.server.pipeline.state.control;

import com.clp.protocol.iec104.apdu.IApdu;
import com.clp.protocol.iec104.apdu.SApdu;
import com.clp.protocol.iec104.apdu.UApdu;
import com.clp.protocol.iec104.definition.quatype.InitCauseQuaType;
import com.clp.protocol.iec104.server.pipeline.PipelineManager;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Nullable;

@Slf4j
public class InitControlStateHandler extends AbstractControlStateHandler {
    @Getter
    private volatile boolean isInitCompleted;

    public InitControlStateHandler(PipelineManager manager) {
        super(manager);
    }

    @Override
    protected void resetState() {
        isInitCompleted = false;
    }

    @Override
    protected void afterResetState() {
        try {
            inSlaveChannel().init();
            // 操作结束，就发送初始化结束报文
            iAsduSender().chSendInitCompleted(InitCauseQuaType.INIT_CAUSE_0);
            isInitCompleted = true; // 不关心是否报文发送成功，直接表示初始化成功
        } catch (Exception e) {
            log.warn("[Control] 初始化失败，即将断开连接");
            channel.close();
        }
    }

    @Override
    protected UApdu updateStateByRecv(UApdu uApdu) {
        return uApdu;
    }

    @Override
    protected SApdu updateStateByRecv(SApdu sApdu) {
        return sApdu;
    }

    @Override
    protected IApdu updateStateByRecv(IApdu iApdu) {
        return iApdu;
    }

    @Override
    protected UApdu updateStateBySend(UApdu uApdu) {
        return uApdu;
    }

    @Override
    protected SApdu updateStateBySend(SApdu sApdu) {
        return sApdu;
    }

    @Override
    protected IApdu updateStateBySend(IApdu iApdu) {
        return iApdu;
//        IAsdu iAsdu = iApdu.getIAsdu();
//        TypeTag typeTag = iAsdu.getTypeTag();
//        if (typeTag != TypeTag.M_EI_NA_1) {
//            return iApdu;
//        }
//        iAsdu
    }

    @Nullable
    @Override
    protected ScheduledTask getScheduledTask() {
        return null;
    }
}
